package controller

import (
	"log"
	"testhttp/model"
	"testhttp/service"
	"time"

	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/sessions"
)

var (
	SessionID = "mysession"
	sess      = sessions.New(sessions.Config{Cookie: SessionID,
		Expires: 45 * time.Minute})
)

func AuthUser(ctx iris.Context) {
	var query model.Authinfo
	query.Username = ctx.URLParam("username")
	query.Password = ctx.URLParam("password")
	query.Captcha = ctx.URLParam("captcha")
	query.Captchaid = ctx.URLParam("captchaid")
	// err := ctx.ReadJSON(&query)
	// if err != nil {
	// 	log.Print("Error:", err)
	// } else {
	verifyCap := service.ProcCaptcha(query.Captchaid, query.Captcha)
	// verifyUser
	varifyUser := service.VarifyUser(query.Username, query.Password)
	log.Print("Debug captcha:", verifyCap)
	if verifyCap && varifyUser { //校验用户及验证码
		session := sess.Start(ctx)
		log.Print("Debug Session create:", session)
		// Authentication goes here
		// ...
		// time.Sleep(4 * 1000 * time.Millisecond)
		// Set user as authenticated
		session.Set("authenticated", true)

		log.Print("Debug Session login: ", session)
		ctx.JSON(iris.Map{
			"Code": "OK",
		})
	} else if verifyCap {
		ctx.JSON(iris.Map{
			"Code": "False",
			"Msg":  verifyCap,
		})
	} else {
		ctx.JSON(iris.Map{
			"Code": "False",
			"Msg":  verifyCap,
		})
	}

	log.Print("Debug Session:", sess)
}

func Logout(ctx iris.Context) {
	session := sess.Start(ctx)

	// Revoke users authentication
	session.Set("authenticated", false)
	// Or to remove the variable:
	session.Delete("authenticated")
	// Or destroy the whole session:
	session.Destroy()
	log.Print("Debug Session logout: ", session)
	ctx.JSON(iris.Map{
		"Code": "OK",
	})
}

func Sec(ctx iris.Context) {
	// Check if user is authenticated
	// reg := regexp.MustCompile(`^*.json.*$|^*.woff.*$|^*.woff2.*$|^*.ttf$|^*.js$|^*.css$|^*.png$|^*.ico$|^*.html$`)

	// if reg.MatchString(ctx.Path()) {
	// 	log.Print("[Test sec]  Comb > ", ctx.Path())
	// 	ctx.Next()
	// } else {
	// 	log.Print("[Test sec] :", ctx.Path(), " 302")
	if auth, _ := sess.Start(ctx).GetBoolean("authenticated"); !auth { //验证session，未通过，跳转login
		ctx.StatusCode(302)
		ctx.Redirect("/login.html?requestUrl=" + ctx.Path())
		return
	}
	ctx.Next()
	// }
}

func Index(ctx iris.Context) {
	log.Print("[Test Index: ]", ctx.GetReferrer().URL)
	ctx.ServeFile("./views" + ctx.Path())
}
